<?php

class AlibabaAction extends CommonAction {
	
	public $cmTableName = 'Alibaba';
	
	
	
	//初始化方法，所有方法必须传 :sessionKey  引入SDK入口文件
	public function _initialize(){
		
		$sessionKey =  empty($_REQUEST['sessionKey'])?'':$_REQUEST['sessionKey'];
		
		$return  	= array();
		
		
		if(empty($sessionKey)){ 
			$return['status'] =  -100;
			$return['msg']    =  '缺少参数:sessionKey';
			die(json_encode($return));
		}
		
		include "./Alibaba/TopSdk.php";
	}
	
	//获取关键词分组
	public function getTagList(){
		
		
		$sessionKey =  empty($_REQUEST['sessionKey'])?'':$_REQUEST['sessionKey'];
		
		
   
		$c = new TopClient; 
		$c->appkey 		= APP_KEY;
		$c->secretKey 	= APP_SECRET;
		
		$req  = new AlibabaScbpTagListRequest; 
		$resp = $c->execute($req, $sessionKey);
		
		$return  = array();
		$return['status'] =  1;
		$return['data']   =  $resp;
		
		$this->returnData($return);
	}
	
	//获取关键词列表
	public function getAdKeyWordList(){
		
		$sessionKey 	=  empty($_REQUEST['sessionKey'])?'':$_REQUEST['sessionKey'];
		$tag_name   	=  empty($_REQUEST['tag_name'])?'':$_REQUEST['tag_name'];
		$per_page_size  =  empty($_REQUEST['per_page_size'])?'20':$_REQUEST['per_page_size'];
		$to_page  		=  empty($_REQUEST['to_page'])?'1':$_REQUEST['to_page'];
		
		$c = new TopClient;
		$c->appkey 		= APP_KEY;
		$c->secretKey 	= APP_SECRET;
		$req = new AlibabaScbpAdKeywordGetRequest;
		$query_dto = new KeywordQuery;
		
		if(!empty($tag_name)){ 
			$query_dto->tag_name		=	$tag_name; 
		}
		
		if(!empty($to_page)){ 
			$query_dto->to_page		=	$to_page; 
		}
		
		$query_dto->per_page_size	=	$per_page_size;
		$req->setQueryDto(json_encode($query_dto));
		$resp = $c->execute($req, $sessionKey);
		
		$return  = array();
		$return['status'] 	=  1;
		$return['data']   	=  $resp;
		$return['tag_name'] =  $tag_name;
		
		$this->returnData($return);
	}
	
	//批量搜索关键词
	public function getAdKeyWordBatch(){
		
		$sessionKey 	=  empty($_REQUEST['sessionKey'])?'':$_REQUEST['sessionKey'];
		$keywordStr 	=  empty($_REQUEST['keywordStr'])?'':$_REQUEST['keywordStr'];
		$is_exact 		=  empty($_REQUEST['is_exact'])?'Y':$_REQUEST['is_exact'];
		
		$keywordArr = explode(DOT,trim($keywordStr,DOT));
		
		$c = new TopClient;
		$c->appkey 		= APP_KEY;
		$c->secretKey 	= APP_SECRET;
		$req = new AlibabaScbpAdKeywordGetRequest;
		$query_dto = new KeywordQuery;
		$query_dto->is_exact="Y";
		
		$allResult = array();
		
		foreach($keywordArr as $keyword){
			
			$query_dto->keyword=$keyword;
			$req->setQueryDto(json_encode($query_dto));
			$resp = $c->execute($req, $sessionKey);
			
			$allResult[] = $resp;
		}
		
		$return  = array();
		$return['status'] =  1;
		$return['data']   =  $allResult;
		
		$this->returnData($return);
		
	}
	
	//获取关键词前5价格
	public function getTopFivePrice(){
		
		$sessionKey =  empty($_REQUEST['sessionKey'])?'':$_REQUEST['sessionKey'];
		$keyword    =  empty($_REQUEST['keyword'])?'':$_REQUEST['keyword'];
		
		$c = new TopClient;
		$c->appkey		= APP_KEY;
		$c->secretKey 	= APP_SECRET;
		
		$req = new AlibabaScbpAdKeywordRankPriceGetRequest;
		$req->setKeyword($keyword);  
		$resp = $c->execute($req, $sessionKey); 
		
		
		$return  = array();
		$return['status'] =  1;
		$return['data']   =  $resp;
		$this->returnData($return);
	}
	
	
	//关键词改价
	public function adKeywordPriceUpdate(){
		
		$sessionKey =  empty($_REQUEST['sessionKey'])?'':$_REQUEST['sessionKey'];
		$keyword 	=  empty($_REQUEST['keyword'])?'':$_REQUEST['keyword'];
		$toPrice 	=  empty($_REQUEST['toPrice'])?'0':$_REQUEST['toPrice'];
		
		if(empty($toPrice)){
			
			$return['status'] =  -1;
			$return['msh']    =  'toPrice:不能为空';
			$this->returnData($return);
		}
		
		$c = new TopClient;
		$c->appkey 		= APP_KEY;
		$c->secretKey 	= APP_SECRET;
		
		$req = new AlibabaScbpAdKeywordPriceUpdateRequest;
		$req->setAdKeyword( $keyword );
		$req->setPriceStr($toPrice);
		$resp = $c->execute($req, $sessionKey);
		
		$return  = array();
		$return['status'] =  1;
		$return['data']   =  $resp;
		$this->returnData($return);
	}
	
	//获取关键词预估排名
	public function getAdKeywordRank(){
		
		$sessionKey =  empty($_REQUEST['sessionKey'])?'':$_REQUEST['sessionKey'];
		$keyword 	=  empty($_REQUEST['keyword'])?'':$_REQUEST['keyword'];
		$index 		=  empty($_REQUEST['index'])?'-1':$_REQUEST['index'];
		
		if(empty($keyword)){
			
			$return['status'] =  -1;
			$return['msh']    =  'keyword:不能为空';
			$this->returnData($return);
		}
		
		$c = new TopClient;
		$c->appkey 		= APP_KEY;
		$c->secretKey   = APP_SECRET;
		$req 			= new AlibabaScbpAdKeywordRankGetRequest;
		
		$req->setKeyword($keyword);
		$resp = $c->execute($req, $sessionKey);
		
		$return  = array();
		$return['status'] =  1;
		$return['index']  =  $index;
		$return['data']   =  $resp;
		$this->returnData($return);
	}
	
	//批量获取关键词预估排名
	public function getAdKeywordRankBatch(){
		
		$sessionKey =  empty($_REQUEST['sessionKey'])?'':$_REQUEST['sessionKey'];
		$keywordStr =  empty($_REQUEST['keywordStr'])?'':$_REQUEST['keywordStr'];
		$index 		=  empty($_REQUEST['index'])?'':$_REQUEST['index'];
		
		$return  = array();
		$return['status'] =  1;
		
		if(empty($keywordStr)){ 
			
			$return['status'] =  0;
			
			$this->returnData($return);
		}
		
		$keywordArr = explode(DOT,$keywordStr);
		
		$c = new TopClient;
		$c->appkey 		= APP_KEY;
		$c->secretKey   = APP_SECRET;
		$req 			= new AlibabaScbpAdKeywordRankGetRequest;
		
		$resArr = array();
		//echo DOT;exit;
		//AAA($keywordArr);
		foreach($keywordArr as $key=>$val){
			
			if(!empty($val)){
				
				$req->setKeyword($val);
				$resp = $c->execute($req, $sessionKey);
				
				$data = array();
				$data['key'] 	=  $val;
				$data['result'] =  $resp;
				
				$resArr[] = $data;
			}
		}
		
		
		$return['data']   =  $resArr;
		$return['index']  =  $index;
		
		$this->returnData($return);
	}
	
	//批量开启，暂停关键词
	public function asyBatchStartOrStopKeywords(){
		
		$sessionKey 	=  empty($_REQUEST['sessionKey'])?'':$_REQUEST['sessionKey'];
		$keywordStr 	=  empty($_REQUEST['keywordStr'])?'':$_REQUEST['keywordStr'];
		$action 		=  empty($_REQUEST['action'])?'':$_REQUEST['action'];
		
		$return  = array();
		$return['status'] =  1;
		
		if(empty($keywordStr)){ 
			
			$return['status'] =  0;
			
			$this->returnData($return);
		}
		
		$keywordArr = explode(DOT,$keywordStr);
		
		$c = new TopClient;
		$c->appkey 		= APP_KEY;
		$c->secretKey   = APP_SECRET;
		$req 			= new AlibabaScbpAdKeywordStatusUpdateRequest;
		
		foreach($keywordArr as $key=>$val){
			
			if(!empty($val)){
				
				$req->setAdKeyword($val);
				
				if($action=='stopped'){
					
					$req->setStatus("stopped");
				}
				
				if($action=='in_promotion'){
					
					$req->setStatus("in_promotion");
				}
				
				$resp = $c->execute($req, $sessionKey);
			}
		}
		
		
		$this->returnData($return);
	}
	
	
	public function muplitUpdatePrice(){
		
		
		$sessionKey 	=  empty($_REQUEST['sessionKey'])?'':$_REQUEST['sessionKey'];
	
		$c = new TopClient;
		$c->appkey = APP_KEY;
		$c->secretKey = APP_SECRET;
		$req = new AlibabaScbpAdKeywordPriceBatchupdateRequest;
		
		$keyword_update_dto_list = new KeywordUpdateDto;
		$str = 						  '[{"keyword_id":"77624451993","value":"4.6"},{"keyword_id":"77625994739","value":"3.2"}]';
		$req->setKeywordUpdateDtoList($str);
		
		$resp = $c->execute($req, $sessionKey);
		
		AAA($resp);
	}
	
	//获取当前生效时段 -> 根据时段获取
	public function getNeedUpdatePriceWords(){
		
		$tempPrice = $_REQUEST['price'];
		$temptop   = $_REQUEST['topprice'];
		$tempbase   = $_REQUEST['baseprice'];
		
		$sessionKey 	= empty($_REQUEST['sessionKey'])?'':$_REQUEST['sessionKey'];
		$username 		= empty($_REQUEST['username'])?'':$_REQUEST['username'];
		
		$member_id 	    = $this->getMemId($username);
		
		$nowHour   = date('G');
		$nowMinute = date('i');
		$nowSecond = date('s');
		$nowTimeStamp = $nowHour.$nowMinute.$nowSecond;
		
		//获取启动的竞价组  1 为启动
		$where = array();
		$where['status'] 	= 1;
		$where['member_id'] = $member_id;
		$groupList = M('bidgroup')->where($where)->select();
		
		foreach($groupList as $keyGropp=>$group){
			
			$where = array();
			$where['group_id']   = $group['bidgroup_id'];
			$where['status']     = 1;
			
			//获取该组已经启动的时间方案
			$strategyList = array();
			$strategyList = M('strategy')->where($where)->select();
			
			foreach($strategyList as $keyStra=>$strategy){
				
				$timeStartArr   = explode(DOT,$strategy['startTime']);
				$timeStartStamp = $timeStartArr[0].getFullTime($timeStartArr[1]).getFullTime($timeStartArr[2]);
				
				$timeEndArr   = explode(DOT,$strategy['endTime']);
				$timeEndStamp = $timeEndArr[0].getFullTime($timeEndArr[1]).getFullTime($timeEndArr[2]);
				
				if( $nowTimeStamp<=$timeEndStamp && $nowTimeStamp>=$timeStartStamp ){
					
					if( empty($groupList[$keyGropp]['strategy']) ){
						
						$groupList[$keyGropp]['strategy'] = $strategy;
					}else{
						if($strategy['is_default']==0){
							$groupList[$keyGropp]['strategy'] = $strategy;
						}
						
					}
					
				}
				
			}
			
		}
		
		//获取竞价组下所有的关键词
		$allWords 	 = array();
		$where 		 = '1 ';
		
		if(!empty($groupList)){
			
			$tempStr = ' AND ( ';
			
			foreach($groupList as $key=>$group){
				
				if($key==0){
					$tempStr.=' bidgroup_id='.$group['bidgroup_id'].' ';
				}
				if($key>0){
					$tempStr.=' OR bidgroup_id='.$group['bidgroup_id'].' ';
				}
				if($key==count($groupList)-1){
					$tempStr.=' ) ';
				}
				
			}
			$where.=$tempStr;
		}
		
		$limit = ' limit 0,2';
		$order = ' ORDER BY last_price_time ASC ';
		$order = ' ';
		$SQL = 'select * from bidgroup_words where '.$where.$order.$limit;
		$allWords = M()->query($SQL);
		
		//循环插入词的组信息，出价格策略信息
		foreach($allWords as $wordKey=>$word){
			
			
			
			foreach($groupList as $group2Key=>$group2){
				
				
				if($group2['bidgroup_id']==$word['bidgroup_id']){
					
					$allWords[$wordKey]['groupInfo'] = $group2;
				}
			}
			
			
		}
		
		
		
		//循环获取词的前5价格，基础价格
		foreach($allWords as $wordKey2=>$word2){
			
			// $c = new TopClient;
			// $c->appkey		= APP_KEY;
			// $c->secretKey 	= APP_SECRET;
			
			// $req = new AlibabaScbpAdKeywordRankPriceGetRequest;
			// $req->setKeyword($word2['keyword']);  
			// $resp = $c->execute($req, $sessionKey);
			
			// $topFiveResult = json_decode(json_encode($resp),true);
			// $topFiveResult = $topFiveResult['rank_price_list']['string'];
			//$allWords[$wordKey2]['topFive'] = json_decode(json_encode($resp),true);
			$allWords[$wordKey2]['topFive'] = $tempPrice;
			
			
			// $req = new AlibabaScbpAdKeywordGetRequest;
			// $query_dto = new KeywordQuery;
			// $query_dto->is_exact="Y";
			// $query_dto->keyword=$word2['keyword'];
			// $req->setQueryDto(json_encode($query_dto));
			// $resp = $c->execute($req, $sessionKey);
			
			// $basePriceResult = json_decode(json_encode($resp),true);
			// $basePriceResult = $basePriceResult['keyword_list']['keyword_result_dto'][0]['base_price'];
			//$allWords[$wordKey2]['baseInfo'] = $basePriceResult;
			$allWords[$wordKey2]['baseInfo'] = $tempbase;
		}
		
		
		//出价数组
		$addPriceList = array();
		foreach($allWords as $wordKey3=>$keyword){
			
			//$tempPrice = $_REQUEST['price'];$temptop   = $_REQUEST['topprice'];
		
			//前5价格
			$topFivePrice = $keyword['topFive'];
			//底价
			$basePrice    = $keyword['baseInfo'];
			//出价方案数组
			$stInfo       = $keyword['groupInfo']['strategy'];
			$price_stept  = $stInfo['price_stept'];
			$top_price    = $stInfo['top_price'];
			
			// $topFiveArr = array();
			// $topFiveArr[0]    = empty($topFivePrice[0])?0.0:$topFivePrice[0];
			// $topFiveArr[1]    = empty($topFivePrice[1])?0.0:$topFivePrice[1];
			// $topFiveArr[2]    = empty($topFivePrice[2])?0.0:$topFivePrice[2];
			// $topFiveArr[3]    = empty($topFivePrice[3])?0.0:$topFivePrice[3];
			// $topFiveArr[4]    = empty($topFivePrice[4])?0.0:$topFivePrice[4];
			
			// $toPriceArr  = array();
			// $toPriceArr[0]	  = $stInfo['first_price']+$price_stept;
			// $toPriceArr[1]	  = $stInfo['second_price']+$price_stept;
			// $toPriceArr[2]	  = $stInfo['third_price']+$price_stept;
			// $toPriceArr[3]	  = $stInfo['fourth_price']+$price_stept;
			// $toPriceArr[4]	  = $stInfo['fifth_price']+$price_stept;
			
			$topFiveArr = array();
			$topFiveArr[0]    = empty($topFivePrice[4])?0.0:$topFivePrice[4];
			$topFiveArr[1]    = empty($topFivePrice[3])?0.0:$topFivePrice[3];
			$topFiveArr[2]    = empty($topFivePrice[2])?0.0:$topFivePrice[2];
			$topFiveArr[3]    = empty($topFivePrice[1])?0.0:$topFivePrice[1];
			$topFiveArr[4]    = empty($topFivePrice[0])?0.0:$topFivePrice[0];
			
			$maxPriceArr  = array();
			$maxPriceArr[0]	  = $stInfo['fifth_price'];
			$maxPriceArr[1]	  = $stInfo['fourth_price'];
			$maxPriceArr[2]	  = $stInfo['third_price'];
			$maxPriceArr[3]	  = $stInfo['second_price'];
			$maxPriceArr[4]	  = $stInfo['first_price'];
			
			$statusArr  = array();
			$statusArr[0] = $stInfo['fifth_status'];
			$statusArr[1] = $stInfo['fourth_status'];
			$statusArr[2] = $stInfo['third_status'];
			$statusArr[3] = $stInfo['second_status'];
			$statusArr[4] = $stInfo['first_status'];
			
			$indexArr = array();
			$indexArr[0] = 4;
			$indexArr[1] = 3;
			$indexArr[2] = 2;
			$indexArr[3] = 1;
			$indexArr[4] = 0;
			
			$price    = 0.0;
			$isPrice  = 1;
			$isSelect = 0;
			$descStr  = '';
			foreach($statusArr as $statusKey=>$nowStatus){
				
				$index2 = $indexArr[$statusKey]+1;
				
				if($nowStatus==1){
					
					if( ($maxPriceArr[$statusKey] >= ($topFiveArr[$statusKey]+$price_stept)) && ($topFiveArr[$statusKey]+$price_stept)<=$top_price ){
						
						$isSelect = 1;
						if($topFiveArr[$statusKey]==0){ 
							$price = $basePrice + $price_stept;
						}else{ 
							$price = $topFiveArr[$statusKey]+$price_stept;
						}
						
						$descStr.='锁定第'.$index2.'名状态为开启:'.$maxPriceArr[$statusKey].'(元)内锁定第'.$index2.'名,第'.$index2.'位置报价为：'.$topFiveArr[$statusKey].'(元),此次计算出价为：'.$price.' 此次计价成功<br>';
					}else{
						$descStr.='锁定第'.$index2.'名状态为开启:'.$maxPriceArr[$statusKey].'(元)内锁定第'.$index2.'名,第'.$index2.'位置报价为：'.$topFiveArr[$statusKey].'(元),此次计算出价为：'.($topFiveArr[$statusKey]+$price_stept).' 此次计价失败<br>';
					}
				}else{
					
					$descStr.='锁定第'.$index2.'名状态为关闭:<br>';
				}
			}
			
			if(!$isSelect){
				
				if( $stInfo['sixth_status']==1 ){
					
					$price = $basePrice + $price_stept;
					$descStr.='其他位置时候，出低价状态为：开启，，当前底价为：'.$basePrice.'(元) ,此次计价为： '.$price.'<br>';
				}else{
					$descStr.='其他位置时候，出低价状态为：关闭.<br>';
				}
				if($stInfo['seventh_status']==1){
					
					if($topFiveArr[0]!=0.0){
						
						$price = $topFiveArr[0]*($stInfo['seventh_price']/100);
					}else{
						$price = $basePrice + 0.1;
					}
					$descStr.='其他位置时按底价x%出价状态为：开启,第5位报价为：'.$topFiveArr[0].'(元)，出价为:'.$price.'='.$topFiveArr[0].'*'.$stInfo['seventh_price'].'/100<br>';
					
				}else{
					
					$descStr.='其他位置时按底价x%出价状态为：关闭<br>';
				}
			}
			
			if($price>$top_price){
				
				$price = $top_price;
				$descStr.='此时计算的出价：'.$price.'大于最大价格:'.$top_price.'(元) ,将出价置为最大出价:'.$top_price.'(元)<br>';
			}else{
				$descStr.='判断此次出价:'.$price.' 在最高出价'.$top_price.' 以内，可以出价<br>';
			}
			
			if($price<($basePrice+0.1)){
				
				$price    = 0.0;
				$isPrice  = 0;
				$descStr.='此时出'.$price.'价仍然小于低价：'.$basePrice.',不出价<br>';
			}else{
				$descStr.='判断此次出价:'.$price.' 大于底价'.$basePrice.' ，可以出价<br>';
			}
			$descStr.='最终出价:'.$price.'<br>';
			$allWords[$wordKey3]['toPrice']  = $price;
			$allWords[$wordKey3]['isPrice']  = $isSelect;
			echo $descStr;
			AAA($allWords);
			
			// $position = '-1';
			
			// $price    = 0.0;
			
			// if( $stInfo['fifth_status']==1 && $toPriceArr[4]>=($topFiveArr[4]+$price_stept) ){
				
				// if($topFiveArr[4]==0){
					// $price = $basePrice + $price_stept;
				// }else{ 
					// $price = $topFiveArr[4]+$price_stept;
				// }
				// $position = 4;
			// }
			
			// if( $stInfo['fourth_status']==1 && $toPriceArr[3]>=($topFiveArr[3]+$price_stept) ){
				
				// if($topFiveArr[3]==0){
					// $price = $basePrice + $price_stept;
				// }else{
					// $price = $topFiveArr[3]+0.1;
				// }
				// $position = 3;
			// }
			
			// if( $stInfo['third_status']==1 && $toPriceArr[2]>=($topFiveArr[2]+$price_stept) ){
				
				// if($topFiveArr[2]==0){
					// $price = $basePrice + $price_stept;
				// }else{
					// $price = $topFiveArr[2]+0.1;
				// }
				// $position = 2;
			// }
			// if( $stInfo['second_status']==1 && $toPriceArr[1]>=($topFiveArr[1]+$price_stept) ){
				
				// if($topFiveArr[1]==0){
					// $price = $basePrice + $price_stept;
				// }else{
					// $price = $topFiveArr[1]+0.1;
				// }
				// $position = 1;
			// }
			
			// if( $stInfo['first_status']==1 && $toPriceArr[0]>=($topFiveArr[0]+$price_stept) ){
				
				// if($topFiveArr[0]==0){
					// $price = $basePrice + $price_stept;
				// }else{
					// $price = $topFiveArr[0]+0.1;
				// }
				// $position = 0;
			// }
			
			// if($position=='-1'){
				
				// if( $stInfo['sixth_status']==1 ){
					
					// $price = $basePrice + $price_stept;
					
				// }
				// if($stInfo['seventh_status']==1){
					
					// if($topFiveArr[4]!=0.0){
						
						// $price = $topFiveArr[4]*($stInfo['seventh_price']/100);
					// }else{
						// $price = $basePrice + 0.1;
					// }
					
					
				// }
			// }
			
			// if($price>=$top_price){
				
				// $price = $top_price;
			// }
			
			// if($price<($basePrice+0.1)){
				
				// $isPrice  = 0;
			// }
			
			// $allWords[$wordKey3]['toPrice']  = $price;
			// $allWords[$wordKey3]['isPrice']  = $isPrice;
			// $allWords[$wordKey3]['position'] = $position;
			
			
		}
		
		
		
			
		$str = '[{"keyword_id":"77624451993","value":"4.6"},{"keyword_id":"77625994739","value":"3.2"}]';
		
		foreach($allWords as $val){
			
			
		}
		
		
		
		AAA($allWords);
		
	}
	
	
	public function test(){
		
		$this->display();
	}
	
	
	
	//返回处理方法
	public function returnData($data){
		
		header("Access-Control-Allow-Origin: *");
		header("Content-type: text/html; charset=utf-8");
		echo json_encode($data);
		exit;
	}
	
	

	
	
	
	
	
	
	
	
	
	
	
	
	public function login_index(){
		
		$appKey    = '24711398';
		$appSecret = '774a0fbc633ded1303fd7a4751a4a653';
	
		$url="https://oauth.alibaba.com/authorize?response_type=code&client_id=".$appKey."&redirect_uri=http://axure.tiansblog.com/taobao-sdk/test3.php&state=huang&sp=icbu";
		
		
		
		
		Header("Location: $url"); 
	}
	
    public function index(){
		
		
	}
	
	
	
	
	//根据阿里巴巴账号获取用户ID
	public function getMemId($username){
		
		$cond = array();
		$cond['username'] = $username;
		
		$userInfo = M('member')->where($cond)->find();
		
		if($userInfo){
			
			return $userInfo['member_id'];
		}else{
			
			return '0';
		}
	}
	
	
	
	
	
	
	
}
?>